AddCSLuaFile("cl_init.lua")
AddCSLuaFile("shared.lua")
include('shared.lua')

function ENT:Initialize()
	self.Entity:SetModel("models/weapons/w_eq_smokegrenade.mdl")
	self.Entity:PhysicsInit(SOLID_VPHYSICS)
	self.Entity:SetMoveType(MOVETYPE_VPHYSICS)
	self.Entity:SetSolid(SOLID_VPHYSICS)
	self.Entity:DrawShadow(false)
	self.Entity:SetCollisionGroup(COLLISION_GROUP_WEAPON)
	local phys = self.Entity:GetPhysicsObject()
	if (phys:IsValid()) then phys:Wake() end
	timer.Simple(math.Rand(1.5,3.5), self.Explode, self)
	timer.Simple(1, self.Solidify, self)
end

function ENT:Think()
	if (ValidEntity(self.Owner)==false) then
		self.Entity:Remove()
	end
	if(ValidEntity(self.Bastardgas)) then 
		local pos = self.Entity:GetPos()
		local maxrange = 512
		local maxstun = 4
		for k,v in pairs(player.GetAll()) do
			local plpos = v:GetPos()
			local dist = -pos:Distance(plpos)+maxrange
				if (pos:Distance(plpos)<=maxrange) then
					local trace = {}
						trace.start = self.Entity:GetPos()
						trace.endpos = v:GetPos()+Vector(0,0,24)
						trace.filter = { v, self.Entity }
						trace.mask = COLLISION_GROUP_PLAYER
					tr = util.TraceLine(trace)
				if (tr.Fraction==1) then
					local stunamount = math.ceil(dist/(maxrange/maxstun))
					PoisonPlayer(v, stunamount, self.Owner, self.Entity)
				end
			end
		end
	end
	self.Entity:NextThink(CurTime()+0.5)
end

function ENT:Solidify()
		self:SetOwner(self.Entity)	
end

function ENT:Remove()
	self:Remove()
end	

function ENT:Explode()
	if (ValidEntity(self.Owner)==false) then
		self.Entity:Remove()
	end
	self.Bastardgas = ents.Create("env_smoketrail")
	self.Bastardgas:SetPos(self.Entity:GetPos())
	self.Bastardgas:SetKeyValue("spawnradius","256")
	self.Bastardgas:SetKeyValue("minspeed","0.5")
	self.Bastardgas:SetKeyValue("maxspeed","2")
	self.Bastardgas:SetKeyValue("startsize","16536")
	self.Bastardgas:SetKeyValue("endsize","256")
	self.Bastardgas:SetKeyValue("endcolor","170 205 70")
	self.Bastardgas:SetKeyValue("startcolor","150 205 70")
	self.Bastardgas:SetKeyValue("opacity","4")
	self.Bastardgas:SetKeyValue("spawnrate","60")
	self.Bastardgas:SetKeyValue("lifetime","10")
	self.Bastardgas:SetParent(self.Entity)
	self.Bastardgas:Spawn()
	self.Bastardgas:Activate()
	self.Bastardgas:Fire("turnon","", 0.1)
	local exp = ents.Create("env_explosion")
	exp:SetKeyValue("spawnflags",461)
	exp:SetPos(self.Entity:GetPos())
	exp:Spawn()
	exp:Fire("explode","",0)
	self.Entity:EmitSound(Sound("BaseSmokeEffect.Sound"))
	timer.Simple(math.Rand(4.5,7.5), self.Remove, self)
end